package com.example.yunhailutong.zhongtan.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.yunhailutong.zhongtan.R;
import com.example.yunhailutong.zhongtan.app.App;
import com.example.yunhailutong.zhongtan.app.OldsEvent;
import com.example.yunhailutong.zhongtan.entity.ImageEntity;
import com.example.yunhailutong.zhongtan.net.PersionBiz;
import com.example.yunhailutong.zhongtan.util.Utils;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.citywheel.CityConfig;
import com.lljjcoder.style.citylist.Toast.ToastUtils;
import com.lljjcoder.style.citypickerview.CityPickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import fr.quentinklein.slt.LocationTracker;
import fr.quentinklein.slt.TrackerSettings;
import me.leefeng.promptlibrary.PromptButton;
import me.leefeng.promptlibrary.PromptButtonListener;
import me.leefeng.promptlibrary.PromptDialog;

/**
 * Created by yunhailutong on 2018/4/26.
 */

public class ActivityUpdateUserMessage extends ActivityBase {


    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.huiyuan_type)
    TextView huiyuanType;
    @BindView(R.id.yonghuming)
    EditText yonghuming;
    @BindView(R.id.gongsimingcheng)
    EditText gongsimingcheng;
    @BindView(R.id.huiyuanjianjie)
    EditText huiyuanjianjie;
    @BindView(R.id.lianxiren)
    EditText lianxiren;
    @BindView(R.id.lianxidinahua)
    EditText lianxidinahua;
    @BindView(R.id.diqu)
    TextView diqu;
    @BindView(R.id.xiangxidizhi)
    EditText xiangxidizhi;
    @BindView(R.id.jingweidu)
    TextView jingweidu;
    @BindView(R.id.chanpinjieshao)
    EditText chanpinjieshao;
    @BindView(R.id.update_register)
    Button updateRegister;
    @BindView(R.id.yingyezhizhao)
    TextView yingyezhizhao;
    @BindView(R.id.rongyuzizhi)
    TextView rongyuzizhi;

    private CityPickerView mPicker;
    private String userTypeId = "";
    private String jignweidus = "";
    private String sheng = "";
    private String shi = "";
    private String qu = "";
    private String yingyezhizhaoImage = "";
    private String rongyizizhiImage = "";
    private PromptDialog promptDialog;

    @Override
    protected void addListener() {

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        diqu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CityConfig cityConfig = new CityConfig.Builder().build();
                mPicker.setConfig(cityConfig);

                //监听选择点击事件及返回结果
                mPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
                    @Override
                    public void onSelected(ProvinceBean province, CityBean city, DistrictBean district) {
                        String s = "";
                        //省份
                        if (province != null) {
                            s = province.getName();
                            sheng = province.getId();
                        }
                        //城市
                        if (city != null) {
                            s = s + city.getName();
                            shi = city.getId();
                        }
                        //地区
                        if (district != null) {
                            s = s + district.getName();
                            qu = district.getId();
                        }
                        diqu.setText(s);
                    }

                    @Override
                    public void onCancel() {
                        ToastUtils.showLongToast(getActivity(), "已取消");
                    }
                });
                //显示
                mPicker.showCityPicker();
            }
        });
        huiyuanType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                initdialog();
            }
        });
    }

    @Override
    protected void initActivity(Bundle savedInstanceState) {
        ButterKnife.bind(this);
    }

    @Override
    protected int contentViewById() {
        return R.layout.activity_update_user_message;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        Map<String, String> params = new HashMap<>();
        params.put("id", App.id);
        params.put("token", App.token);
        new PersionBiz().GetUserInfo(params);
        showWaitingDialog();
        mPicker = new CityPickerView();
        mPicker.init(this);
        updateRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!Utils.isMobileNO(lianxidinahua.getText().toString())) {
                    disPlay("请输入有效的手机号");
                } else if (lianxiren.getText().toString().equals("")) {
                    disPlay("联系人不能为空");
                } else if (gongsimingcheng.getText().toString().equals("")) {
                    disPlay("车牌号不能为空");
                } else if (yonghuming.getText().toString().equals("")) {
                    disPlay("用户名不能为空");
                } else if (huiyuanjianjie.getText().toString().equals("")) {
                    disPlay("会员简介不能为空");
                } else if (diqu.getText().toString().equals("")) {
                    disPlay("请先选择地区");
                } else if (xiangxidizhi.getText().toString().equals("")) {
                    disPlay("详细地址不能为空");
                } else if (jingweidu.getText().toString().equals("")) {
                    disPlay("经纬度不能为空");
                } else if (chanpinjieshao.getText().toString().equals("")) {
                    disPlay("产品简介不能为空");
                } else if (userTypeId.equals("")) {
                    disPlay("请先选择会员类型");
                } else if (rongyizizhiImage.equals("")) {
                    disPlay("请先上传荣誉资质");
                } else if (yingyezhizhaoImage.equals("")) {
                    disPlay("请先上传营业执照");
                } else {
                    Map<String, String> params = new HashMap<>();
                    params.put("id", App.id);
                    params.put("token", App.token);
                    params.put("account", yonghuming.getText().toString());
                    params.put("name", lianxiren.getText().toString());
                    params.put("mtype", userTypeId);
                    params.put("info", huiyuanjianjie.getText().toString());
                    params.put("province", sheng);
                    params.put("city", shi);
                    params.put("area", qu);
                    params.put("address", xiangxidizhi.getText().toString());
                    params.put("position", jignweidus);
                    params.put("contacts", lianxiren.getText().toString());
                    params.put("phone", lianxidinahua.getText().toString());
                    params.put("businesslicense", yingyezhizhaoImage);
                    params.put("honor", rongyizizhiImage);
                    new PersionBiz().updateMessage(params);
                    showWaitingDialog();
                }
            }
        });
        dingwei();
        yingyezhizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(ActivityUpdateUserMessage.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .forResult(188);//结果回调onActivityResult code
            }
        });
        rongyuzizhi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PictureSelector.create(ActivityUpdateUserMessage.this)
                        .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                        .maxSelectNum(1)// 最大图片选择数量 int
                        .minSelectNum(1)// 最小选择数量 int
                        .imageSpanCount(4)// 每行显示个数 int
                        .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                        .previewImage(true)// 是否可预览图片 true or false
                        .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                        .forResult(189);//结果回调onActivityResult code
            }
        });

    }

    private void dingwei() {
        TrackerSettings trackerSettings = new TrackerSettings();
        trackerSettings.setUseGPS(true).setUseNetwork(true).setUsePassive(true).setTimeout(5000);
        LocationTracker locationTracker = new LocationTracker(this, trackerSettings) {
            public void onLocationFound(Location location) {
                if (location != null) {
                    jingweidu.setText("您当前的经纬度是：" + location.getLongitude() + "," + location.getLatitude());
                    jignweidus = "" + location.getLongitude() + "," + location.getLatitude();
                }
            }

            public void onTimeout() {
                jingweidu.setText("没有定位权限，请去设置中打开定位权限后重试");
            }
        };
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationTracker.startListening();
    }

    @Subscribe
    public void log(OldsEvent.GetUserInfoEvent msg) {
        dismissWaitingDialog();
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        }
        if (msg.what == 1) {
        }
    }
    @Subscribe
    public void log(OldsEvent.UpDateInfoEvent msg) {
        dismissWaitingDialog();
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        }
        if (msg.what == 1) {
            disPlay("上传成功");
            finish();
        }
    }
    @Subscribe
    public void logs(OldsEvent.UpLoadImageEvent msg) {
        dismissWaitingDialog();
        if (msg.what == -1) {
            disPlay(msg.obj.toString());
        }
        if (msg.what == 1) {
            ImageEntity entity = (ImageEntity) msg.obj;
            if (msg.arg1.equals("1")) {
                yingyezhizhaoImage = entity.getFileNameList().get(0).getImgName();
                yingyezhizhao.setText("图片已上传");
            } else {
                rongyizizhiImage = entity.getFileNameList().get(0).getImgName();
                rongyuzizhi.setText("图片已上传");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 188:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    final File file1 = new File(selectList.get(0).getPath());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            new PersionBiz().uploadImage("1","info", file1);
                        }
                    }).start();
                    showWaitingDialog();
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
                case 189:
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList2 = PictureSelector.obtainMultipleResult(data);
                    final File file2 = new File(selectList2.get(0).getPath());
                    //   params.put("username", userNameRegister.getText().toString());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            new PersionBiz().uploadImage("2","info", file2);

                        }
                    }).start();
                    showWaitingDialog();
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        }
    }

    private void initdialog() {
        promptDialog = new PromptDialog(this);

        //可创建android效果的底部Sheet选择，默认IOS效果，sheetCellPad=0为Android效果的Sheet
        //                promptDialog.getAlertDefaultBuilder().sheetCellPad(0).round(0);
        //设置按钮的特点，颜色大小什么的，具体看PromptButton的成员变量
        PromptButton cancle = new PromptButton("取消", null);
        cancle.setTextColor(Color.parseColor("#0076ff"));
        //设置显示的文字大小及颜色
        promptDialog.getAlertDefaultBuilder().textColor(Color.GRAY);
        promptDialog.showAlertSheet("", true, cancle, new PromptButton("企业会员", new PromptButtonListener() {
            @Override
            public void onClick(PromptButton promptButton) {
                huiyuanType.setText("企业会员");
                userTypeId = "0";
            }
        }), new PromptButton("个人会员", new PromptButtonListener() {
            @Override
            public void onClick(PromptButton promptButton) {
                huiyuanType.setText("个人会员");
                userTypeId = "1";
            }
        }));
    }

}
